<template>
    <div class="hospital-departments">
        <h4>医院科室管理</h4>

        <!-- 科室列表 -->
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>科室列表</span>
                    <el-button type="primary" @click="showAddDepartmentModal">新增科室</el-button>
                </div>
            </template>

            <!-- 科室表格 -->
            <el-table ref="departmentTableRef" :data="departments" style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="name" label="科室名称" />
                <el-table-column prop="level" label="级别" width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.level === '一级' ? 'primary' : 'success'">
                            {{ scope.row.level }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === '显示' ? 'success' : 'info'">
                            {{ scope.row.status }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="remarks" label="备注">
                    <template #default="scope">
                        <span :title="scope.row.remarks">
                            {{ scope.row.remarks && scope.row.remarks.length > 10
                                ? scope.row.remarks.substring(0, 10) + '...'
                                : scope.row.remarks }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="uploader" label="上传人" width="100">
                    <template v-slot="scoped">
                        admin
                    </template>
                </el-table-column>
                <el-table-column prop="addTime" label="添加时间" width="180" />
                <el-table-column label="操作" width="300">
                    <template #default="scope">
                        <el-button v-if="scope.row.level === '一级'" type="primary" size="small"
                            @click="directAddSubDepartment(scope.row)">新增下级</el-button>
                        <el-button v-if="scope.row.level === '一级'" type="info" size="small"
                            @click="viewSubDepartments(scope.row)">
                            查看下级
                        </el-button>
                        <el-button type="warning" size="small" @click="editDepartment(scope.row)">
                            编辑
                        </el-button>
                        <el-button type="danger" size="small" @click="deleteDepartment(scope.row)"
                            :disabled="isDeleting" :loading="isDeleting">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 批量操作和分页 -->
            <div class="table-footer">
                <div class="batch-operations">
                    <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
                    <el-button type="danger" size="small" @click="batchDelete"
                        :disabled="selectedDepartments.length === 0 || isDeleting" :loading="isDeleting">
                        批量删除
                    </el-button>
                </div>
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 新增/编辑科室模态框 -->
        <el-dialog v-model="departmentModalVisible" :title="isEdit ? '编辑科室' : '新增科室'" width="500px">
            <el-form :model="departmentForm" :rules="departmentRules" ref="departmentFormRef" label-width="100px">
                <el-form-item label="科室名称" prop="name">
                    <el-input v-model="departmentForm.name" placeholder="请输入科室名称" />
                </el-form-item>
                <el-form-item label="上级分类" prop="parentId">
                    <el-select v-model="departmentForm.parentId" placeholder="请选择上级分类，不选择默认为无分类" clearable>
                        <el-option v-for="dept in topLevelDepartments" :key="dept.id" :label="dept.name"
                            :value="dept.id" />
                    </el-select>
                    <div class="form-tip">不选择分类默认为无分类（顶级科室）</div>
                </el-form-item>
                <el-form-item label="备注" prop="remarks">
                    <el-input v-model="departmentForm.remarks" type="textarea" :rows="4" placeholder="请输入备注信息"
                        show-word-limit maxlength="140" />
                </el-form-item>
                <el-form-item label="是否显示" prop="status">
                    <el-radio-group v-model="departmentForm.status">
                        <el-radio :value="'显示'">是</el-radio>
                        <el-radio :value="'隐藏'">否</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="departmentModalVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveDepartment">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 二级分类管理模态框 -->
        <el-dialog v-model="subDepartmentModalVisible" :title="isViewOnlyMode ? '查看二级分类' : '二级分类管理'" width="800px"
            @close="isViewOnlyMode = false">
            <div class="sub-department-header">
                <h5>当前科室：{{ currentParentDepartment?.name }}</h5>
                <el-button v-if="!isViewOnlyMode" type="primary" @click="showAddSubDepartmentModal">新增二级分类</el-button>
            </div>

            <el-table :data="subDepartments" style="width: 100%">
                <el-table-column prop="departmentName" label="二级分类名称" />
                <el-table-column prop="departmentGrade" label="级别" width="100">
                    <template #default="scope">
                        <el-tag type="success">{{ scope.row.departmentGrade === 2 ? '二级' : '一级' }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="departmentStatus" label="状态" width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.departmentStatus ? 'success' : 'info'">
                            {{ scope.row.departmentStatus ? '显示' : '隐藏' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="departmentRemarks" label="备注">
                    <template #default="scope">
                        <span :title="scope.row.departmentRemarks">
                            {{ scope.row.departmentRemarks && scope.row.departmentRemarks.length > 10
                                ? scope.row.departmentRemarks.substring(0, 10) + '...'
                                : scope.row.departmentRemarks }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="createdBy" label="上传人" width="100">
                    <template #default="scope">
                        admin
                    </template>
                </el-table-column>
                <el-table-column prop="createdTime" label="添加时间" width="180">
                    <template #default="scope">
                        {{ new Date(scope.row.createdTime).toLocaleString() }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                    <template #default="scope">
                        <el-button type="warning" size="small" @click="editSubDepartment(scope.row)">
                            编辑
                        </el-button>
                        <el-button type="danger" size="small" @click="deleteSubDepartment(scope.row)"
                            :disabled="isDeleting" :loading="isDeleting">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>

        <!-- 新增/编辑二级分类模态框 -->
        <el-dialog v-model="subDepartmentFormModalVisible" :title="isEditSub ? '编辑二级分类' : '新增二级分类'" width="500px">
            <el-form :model="subDepartmentForm" :rules="subDepartmentRules" ref="subDepartmentFormRef"
                label-width="100px">
                <el-form-item label="分类名称" prop="name">
                    <el-input v-model="subDepartmentForm.name" placeholder="请输入二级分类名称" />
                </el-form-item>
                <el-form-item label="上级科室" prop="parentId">
                    <el-input :model-value="currentParentDepartment?.name || ''" disabled readonly
                        placeholder="请先选择一级科室" />
                    <div class="form-tip">上级科室为当前选中的一级科室，不可修改</div>
                </el-form-item>
                <el-form-item label="备注" prop="remarks">
                    <el-input v-model="subDepartmentForm.remarks" type="textarea" :rows="4" placeholder="请输入备注信息"
                        show-word-limit maxlength="140" />
                </el-form-item>
                <el-form-item label="是否显示" prop="status">
                    <el-radio-group v-model="subDepartmentForm.status">
                        <el-radio :value="'显示'">是</el-radio>
                        <el-radio :value="'隐藏'">否</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="subDepartmentFormModalVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveSubDepartment">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { readB, writeB } from '@/api/http'

// 数据类型定义
interface Department {
    "id": number,
    "departmentName": string,
    "departmentGrade": number,
    "departmentStatus": boolean,
    "departmentRemarks": string,
    "parentId": number,
    "createdTime": string,
    "createdBy": number
}

// 显示用的科室数据格式
interface DisplayDepartment {
    id: number,
    name: string,
    level: string,
    status: string,
    remarks: string,
    uploader: string,
    addTime: string,
    parentId?: number
}

// 响应式数据
const departments = ref<DisplayDepartment[]>([])
const selectedDepartments = ref<DisplayDepartment[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectAll = ref(false)

// 模态框控制
const departmentModalVisible = ref(false)
const subDepartmentModalVisible = ref(false)
const subDepartmentFormModalVisible = ref(false)
const isEdit = ref(false)
const isEditSub = ref(false)
const isViewOnlyMode = ref(false) // 是否为只查看模式（不显示新增按钮）
const isDeleting = ref(false) // 是否正在删除中（防止重复操作）

// 表单数据
const departmentForm = reactive({
    id: 0,
    name: '',
    parentId: undefined as number | undefined,
    remarks: '',
    status: '显示' as '显示' | '隐藏'
})

const subDepartmentForm = reactive({
    id: 0,
    name: '',
    parentId: 0,
    remarks: '',
    status: '显示' as '显示' | '隐藏'
})

// 当前操作的父级科室
const currentParentDepartment = ref<DisplayDepartment | null>(null)
const subDepartments = ref<Department[]>([])

// 所有一级科室数据（用于上级分类选择）
const allFirstLevelDepartments = ref<DisplayDepartment[]>([])

// 表单验证规则
const departmentRules = {
    name: [
        { required: true, message: '请输入科室名称', trigger: 'blur' },
        { min: 1, max: 50, message: '科室名称长度在1到50个字符', trigger: 'blur' }
    ]
}

const subDepartmentRules = {
    name: [
        { required: true, message: '请输入二级分类名称', trigger: 'blur' },
        { min: 1, max: 50, message: '二级分类名称长度在1到50个字符', trigger: 'blur' }
    ]
}

// 表单引用
const departmentFormRef = ref()
const subDepartmentFormRef = ref()
const departmentTableRef = ref()

// 计算属性
const topLevelDepartments = computed(() => {
    return allFirstLevelDepartments.value.length > 0
        ? allFirstLevelDepartments.value
        : departments.value.filter(dept => dept.level === '一级' && (!dept.parentId || dept.parentId === 0))
})

// 初始化数据
onMounted(() => {
    loadDepartments()
    loadAllFirstLevelDepartments() // 初始化时加载所有一级科室
})

// 加载科室数据
const loadDepartments = async () => {
    try {
        // 支持分页的API调用
        const params = {
            PageIndex: currentPage.value,
            PageSize: pageSize.value
        }

        const response = await readB.get('/api/Department/GetFirstLevelDepartments/first-level', { params })

        if (response.data) {
            let departmentList: Department[] = []
            let totalCount = 0

            // 检查API返回的数据格式
            if (Array.isArray(response.data)) {
                // 如果返回的是数组，直接使用
                departmentList = response.data
                totalCount = response.data.length
            } else if (response.data.data && Array.isArray(response.data.data)) {
                // 如果返回的是分页格式 { data: [], total: number }
                departmentList = response.data.data
                totalCount = response.data.total || response.data.data.length
            } else if (response.data.items && Array.isArray(response.data.items)) {
                // 如果返回的是分页格式 { items: [], total: number }
                departmentList = response.data.items
                totalCount = response.data.total || response.data.items.length
            }

            // 转换API数据格式为显示格式
            departments.value = departmentList.map((dept: Department) => ({
                id: dept.id,
                name: dept.departmentName,
                level: (dept.departmentGrade === 1 || dept.parentId === 0) ? '一级' : '二级',
                status: dept.departmentStatus ? '显示' : '隐藏',
                remarks: dept.departmentRemarks || '',
                uploader: `用户${dept.createdBy}`, // 这里可以根据实际需求调用用户API获取用户名
                addTime: new Date(dept.createdTime).toLocaleString(),
                parentId: dept.parentId
            }))

            total.value = totalCount

            // 重置选择状态
            selectedDepartments.value = []
            selectAll.value = false

        } else {
            console.error('API返回数据格式错误:', response.data)
            ElMessage.error('数据格式错误')
        }
    } catch (error) {
        console.error('加载科室数据失败:', error)
        ElMessage.error('加载科室数据失败，请检查网络连接')

        // 如果API调用失败，使用备用数据
        departments.value = [
            {
                id: 1,
                name: '内科',
                level: '一级',
                status: '显示',
                remarks: '内科科室',
                uploader: 'admin',
                addTime: new Date().toLocaleString(),
                parentId: undefined
            }
        ]
        total.value = departments.value.length
    }
}

// 加载所有一级科室（用于上级分类选择）
const loadAllFirstLevelDepartments = async () => {
    try {
        // 调用API获取所有一级科室，不分页
        const params = {
            PageIndex: 1,
            PageSize: 1000, // 设置大页面以获取所有一级科室
            DepartmentGrade: 1 // 只获取一级科室
        }

        const response = await readB.get('/api/Department/GetFirstLevelDepartments/first-level', { params })

        if (response.data) {
            let departmentList: Department[] = []

            // 检查API返回的数据格式
            if (Array.isArray(response.data)) {
                departmentList = response.data.filter((dept: Department) => dept.departmentGrade === 1 || dept.parentId === 0)
            } else if (response.data.data && Array.isArray(response.data.data)) {
                departmentList = response.data.data.filter((dept: Department) => dept.departmentGrade === 1 || dept.parentId === 0)
            } else if (response.data.items && Array.isArray(response.data.items)) {
                departmentList = response.data.items.filter((dept: Department) => dept.departmentGrade === 1 || dept.parentId === 0)
            }

            // 转换API数据格式为显示格式
            allFirstLevelDepartments.value = departmentList.map((dept: Department) => ({
                id: dept.id,
                name: dept.departmentName,
                level: '一级',
                status: dept.departmentStatus ? '显示' : '隐藏',
                remarks: dept.departmentRemarks || '',
                uploader: `用户${dept.createdBy}`,
                addTime: new Date(dept.createdTime).toLocaleString(),
                parentId: dept.parentId || 0  // 确保parentId为数字
            }))

            console.log('加载到一级科室:', allFirstLevelDepartments.value.length, '个')
        }
    } catch (error) {
        console.error('加载一级科室失败:', error)
        // 如果API调用失败，使用当前页面的一级科室数据
        allFirstLevelDepartments.value = departments.value.filter(dept => dept.level === '一级')
    }
}

// 显示新增科室模态框
const showAddDepartmentModal = async () => {
    isEdit.value = false
    resetDepartmentForm()

    // 如果还没有加载一级科室数据，则加载
    if (allFirstLevelDepartments.value.length === 0) {
        await loadAllFirstLevelDepartments()
    }

    departmentModalVisible.value = true
}

// 编辑科室
const editDepartment = async (department: DisplayDepartment) => {
    isEdit.value = true

    // 将DisplayDepartment格式转换为表单需要的格式
    Object.assign(departmentForm, {
        id: department.id,
        name: department.name,
        parentId: department.parentId || undefined, // 确保0值转换为undefined以正确显示下拉框
        remarks: department.remarks,
        status: department.status
    })

    // 如果还没有加载一级科室数据，则加载
    if (allFirstLevelDepartments.value.length === 0) {
        await loadAllFirstLevelDepartments()
    }

    departmentModalVisible.value = true
}

// 删除科室
const deleteDepartment = async (department: DisplayDepartment) => {
    if (isDeleting.value) {
        ElMessage.warning('正在删除中，请稍候...')
        return
    }

    try {
        await ElMessageBox.confirm(
            `确定要删除科室"${department.name}"吗？`,
            '确认删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        // 调用后端批量删除API（单个删除）
        isDeleting.value = true
        try {
            const requestData = {
                departmentIds: [department.id]
            }

            console.log('提交删除科室数据:', requestData)

            const response = await writeB.delete('/api/Department/BatchDeleteDepartment/batch-delete', {
                data: requestData
            })

            console.log('删除科室响应:', response.data)

            if (response.data.code == 200) {
                ElMessage.success('删除科室成功')

                // 重新加载科室列表
                await loadDepartments()

                // 重新加载一级科室数据（用于下拉选择）
                await loadAllFirstLevelDepartments()
            } else {
                ElMessage.error(response.data.message)
            }
        } catch (error: any) {
            console.error('删除科室失败:', error)

            // 检查错误响应
            if (error.response && error.response.data) {
                const errorMessage = error.response.data.message || error.response.data.title || '删除科室失败'
                ElMessage.error(errorMessage)
            } else {
                ElMessage.error('删除科室失败，请检查网络连接')
            }
        } finally {
            isDeleting.value = false
        }
    } catch {
        // 用户取消删除
    }
}

// 保存科室
const saveDepartment = async () => {
    if (!departmentFormRef.value) return

    try {
        await departmentFormRef.value.validate()

        if (isEdit.value) {
            // 编辑模式 - 调用后端API
            try {
                const requestData = {
                    id: departmentForm.id,
                    departmentName: departmentForm.name,
                    departmentGrade: (departmentForm.parentId && departmentForm.parentId !== 0) ? 2 : 1,
                    departmentStatus: departmentForm.status === '显示',
                    departmentRemarks: departmentForm.remarks || '',
                    parentId: departmentForm.parentId || 0
                }

                console.log('提交编辑科室数据:', requestData)

                const response = await writeB.put('/api/Department/UpdateDepartment/update', requestData)

                console.log('编辑科室响应:', response.data)

                if (response.data && (response.status === 200 || response.status === 204)) {
                    ElMessage.success('编辑科室成功')

                    // 重新加载科室列表
                    await loadDepartments()

                    // 重新加载一级科室数据（用于下拉选择）
                    await loadAllFirstLevelDepartments()
                } else {
                    ElMessage.error('编辑科室失败，请检查数据')
                }
            } catch (error: any) {
                console.error('编辑科室失败:', error)

                // 检查错误响应
                if (error.response && error.response.data) {
                    const errorMessage = error.response.data.message || error.response.data.title || '编辑科室失败'
                    ElMessage.error(errorMessage)
                } else {
                    ElMessage.error('编辑科室失败，请检查网络连接')
                }
                return // 出错时不关闭对话框
            }
        } else {
            // 新增模式 - 调用后端API
            try {
                const requestData = {
                    departmentName: departmentForm.name,
                    departmentStatus: departmentForm.status === '显示',
                    departmentRemarks: departmentForm.remarks || '',
                    parentId: departmentForm.parentId || 0  // 不选择上级分类时默认为0（无分类）
                }

                console.log('提交新增科室数据:', requestData)

                const response = await writeB.post('/api/Department/AddDepartment/add', requestData)

                console.log('新增科室响应:', response.data)

                if (response.data && (response.status === 200 || response.status === 201)) {
                    ElMessage.success('新增科室成功')

                    // 重新加载科室列表
                    await loadDepartments()

                    // 重新加载一级科室数据（用于下拉选择）
                    await loadAllFirstLevelDepartments()
                } else {
                    ElMessage.error('新增科室失败，请检查数据')
                }
            } catch (error: any) {
                console.error('新增科室失败:', error)

                // 检查错误响应
                if (error.response && error.response.data) {
                    const errorMessage = error.response.data.message || error.response.data.title || '新增科室失败'
                    ElMessage.error(errorMessage)
                } else {
                    ElMessage.error('新增科室失败，请检查网络连接')
                }
                return // 出错时不关闭对话框
            }
        }

        departmentModalVisible.value = false
    } catch (error) {
        console.error('表单验证失败:', error)
    }
}

// 重置科室表单
const resetDepartmentForm = () => {
    Object.assign(departmentForm, {
        id: 0,
        name: '',
        parentId: undefined, // 不选择默认为无分类
        remarks: '',
        status: '显示'
    })
}

// 选择相关
const handleSelectionChange = (selection: DisplayDepartment[]) => {
    selectedDepartments.value = selection
    // 只有当有数据且全部选中时才设置为true，否则为false
    selectAll.value = departments.value.length > 0 && selection.length === departments.value.length
}

const handleSelectAll = (val: boolean) => {
    if (departmentTableRef.value) {
        if (val) {
            // 全选所有行
            departments.value.forEach(row => {
                departmentTableRef.value.toggleRowSelection(row, true)
            })
        } else {
            // 取消全选
            departmentTableRef.value.clearSelection()
        }
    }
}

// 批量删除
const batchDelete = async () => {
    if (selectedDepartments.value.length === 0) {
        ElMessage.warning('请选择要删除的科室')
        return
    }

    if (isDeleting.value) {
        ElMessage.warning('正在删除中，请稍候...')
        return
    }

    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedDepartments.value.length} 个科室吗？`,
            '确认批量删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        // 调用后端批量删除API
        const deleteCount = selectedDepartments.value.length
        isDeleting.value = true
        try {
            const ids = selectedDepartments.value.map(d => d.id)
            const requestData = {
                departmentIds: ids
            }

            console.log('提交批量删除科室数据:', requestData)

            const response = await writeB.delete('/api/Department/BatchDeleteDepartment/batch-delete', {
                data: requestData
            })

            console.log('批量删除科室响应:', response.data)

            if (response.data.code == 200) {
                ElMessage.success(`成功删除 ${deleteCount} 个科室`)

                // 清空选择状态
                selectedDepartments.value = []
                selectAll.value = false

                // 重新加载科室列表
                await loadDepartments()

                // 重新加载一级科室数据（用于下拉选择）
                await loadAllFirstLevelDepartments()
            } else {
                ElMessage.error(response.data.message)
            }
        } catch (error: any) {
            console.error('批量删除科室失败:', error)

            // 检查错误响应
            if (error.response && error.response.data) {
                const errorMessage = error.response.data.message || error.response.data.title || '批量删除科室失败'
                ElMessage.error(errorMessage)
            } else {
                ElMessage.error('批量删除科室失败，请检查网络连接')
            }
        } finally {
            isDeleting.value = false
        }
    } catch {
        // 用户取消删除
    }
}

// 分页相关
const handleSizeChange = (val: number) => {
    pageSize.value = val
    currentPage.value = 1  // 重置到第一页
    loadDepartments()
}

const handleCurrentChange = (val: number) => {
    currentPage.value = val
    loadDepartments()
}

// 二级分类相关
const addSubDepartment = (department: DisplayDepartment) => {
    currentParentDepartment.value = department
    isViewOnlyMode.value = false // 设置为可编辑模式（显示新增按钮）
    loadSubDepartments(department.id)
    subDepartmentModalVisible.value = true
}

// 直接新增下级科室（不打开二级分类管理页面）
const directAddSubDepartment = (department: DisplayDepartment) => {
    currentParentDepartment.value = department
    isViewOnlyMode.value = false // 设置为可编辑模式
    isEditSub.value = false
    resetSubDepartmentForm()
    subDepartmentFormModalVisible.value = true
}

const viewSubDepartments = (department: DisplayDepartment) => {
    currentParentDepartment.value = department
    isViewOnlyMode.value = true // 设置为只查看模式
    loadSubDepartments(department.id)
    subDepartmentModalVisible.value = true
}

const loadSubDepartments = async (parentId: number) => {
    console.log(parentId)
    try {
        // 调用API获取二级科室数据，传递父级ID参数
        const params = {
            ParendId: parentId

        }

        const response = await readB.get('/api/Department/GetFirstLevelDepartments/first-level', { params })

        console.log("二级科室查询", response.data.data)
        if (response.data) {
            let departmentList: Department[] = []

            // 检查API返回的数据格式
            if (Array.isArray(response.data)) {
                // 如果返回的是数组，筛选出父级ID匹配的二级科室
                departmentList = response.data.filter((dept: Department) =>
                    dept.parentId === parentId && dept.departmentGrade === 2
                )
            } else if (response.data.data && Array.isArray(response.data.data)) {
                // 如果返回的是分页格式 { data: [], total: number }
                departmentList = response.data.data.filter((dept: Department) =>
                    dept.parentId === parentId && dept.departmentGrade === 2
                )
            } else if (response.data.items && Array.isArray(response.data.items)) {
                // 如果返回的是分页格式 { items: [], total: number }
                departmentList = response.data.items.filter((dept: Department) =>
                    dept.parentId === parentId && dept.departmentGrade === 2
                )
            }

            subDepartments.value = departmentList

            if (departmentList.length > 0) {
                ElMessage.success(`加载到 ${departmentList.length} 个二级科室`)
            } else {
                ElMessage.info('该科室下暂无二级分类')
                // 如果没有数据，显示空状态
                subDepartments.value = []
            }
        } else {
            console.error('API返回数据格式错误:', response.data)
            ElMessage.error('数据格式错误')
            subDepartments.value = []
        }
    } catch (error) {
        console.error('加载二级分类失败:', error)
        ElMessage.error('加载二级分类失败，请检查网络连接')

        // 如果API调用失败，显示空数据
        subDepartments.value = []
    }
}

const showAddSubDepartmentModal = () => {
    isEditSub.value = false
    isViewOnlyMode.value = false // 确保为可编辑模式
    resetSubDepartmentForm()

    // 检查是否已选择上级科室
    if (!currentParentDepartment.value) {
        ElMessage.warning('请先选择一级科室')
        return
    }

    subDepartmentFormModalVisible.value = true
}

const editSubDepartment = async (subDepartment: Department) => {
    isEditSub.value = true

    // 将Department数据转换为表单格式
    Object.assign(subDepartmentForm, {
        id: subDepartment.id,
        name: subDepartment.departmentName,
        parentId: subDepartment.parentId, // 保持原有的parentId，但界面上不可编辑
        remarks: subDepartment.departmentRemarks,
        status: subDepartment.departmentStatus ? '显示' : '隐藏'
    })

    // 确保currentParentDepartment设置正确（用于显示上级科室名称）
    if (!currentParentDepartment.value && subDepartment.parentId) {
        // 从allFirstLevelDepartments中找到对应的父级科室
        if (allFirstLevelDepartments.value.length === 0) {
            await loadAllFirstLevelDepartments()
        }

        const parentDept = allFirstLevelDepartments.value.find(dept => dept.id === subDepartment.parentId)
        if (parentDept) {
            currentParentDepartment.value = parentDept
        }
    }

    subDepartmentFormModalVisible.value = true
}

const deleteSubDepartment = async (subDepartment: Department) => {
    if (isDeleting.value) {
        ElMessage.warning('正在删除中，请稍候...')
        return
    }

    try {
        await ElMessageBox.confirm(
            `确定要删除二级分类"${subDepartment.departmentName}"吗？`,
            '确认删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        // 调用后端批量删除API（单个删除）
        isDeleting.value = true
        try {
            const requestData = {
                departmentIds: [subDepartment.id]
            }

            console.log('提交删除二级科室数据:', requestData)

            const response = await writeB.delete('/api/Department/BatchDeleteDepartment/batch-delete', {
                data: requestData
            })

            console.log('删除二级科室响应:', response.data)

            if (response.status === 200 || response.status === 204) {
                ElMessage.success('删除二级科室成功')

                // 重新加载二级科室列表
                if (currentParentDepartment.value) {
                    await loadSubDepartments(currentParentDepartment.value.id)
                }

                // 重新加载主科室列表
                await loadDepartments()

                // 重新加载一级科室数据
                await loadAllFirstLevelDepartments()
            } else {
                ElMessage.error('删除二级科室失败，请检查数据')
            }
        } catch (error: any) {
            console.error('删除二级科室失败:', error)

            // 检查错误响应
            if (error.response && error.response.data) {
                const errorMessage = error.response.data.message || error.response.data.title || '删除二级科室失败'
                ElMessage.error(errorMessage)
            } else {
                ElMessage.error('删除二级科室失败，请检查网络连接')
            }
        } finally {
            isDeleting.value = false
        }
    } catch {
        // 用户取消删除
    }
}

const saveSubDepartment = async () => {
    if (!subDepartmentFormRef.value) return

    try {
        await subDepartmentFormRef.value.validate()

        if (isEditSub.value) {
            // 编辑模式 - 调用后端API
            try {
                const requestData = {
                    id: subDepartmentForm.id,
                    departmentName: subDepartmentForm.name,
                    departmentGrade: 2, // 二级科室
                    departmentStatus: subDepartmentForm.status === '显示',
                    departmentRemarks: subDepartmentForm.remarks || '',
                    parentId: currentParentDepartment.value?.id || subDepartmentForm.parentId
                }

                console.log('提交编辑二级科室数据:', requestData)

                const response = await writeB.put('/api/Department/UpdateDepartment/update', requestData)

                console.log('编辑二级科室响应:', response.data)

                if (response.data && (response.status === 200 || response.status === 204)) {
                    ElMessage.success('编辑二级科室成功')

                    // 重新加载二级科室列表
                    if (currentParentDepartment.value) {
                        await loadSubDepartments(currentParentDepartment.value.id)
                    }

                    // 重新加载主科室列表
                    await loadDepartments()

                    // 重新加载一级科室数据
                    await loadAllFirstLevelDepartments()
                } else {
                    ElMessage.error('编辑二级科室失败，请检查数据')
                }
            } catch (error: any) {
                console.error('编辑二级科室失败:', error)

                // 检查错误响应
                if (error.response && error.response.data) {
                    const errorMessage = error.response.data.message || error.response.data.title || '编辑二级科室失败'
                    ElMessage.error(errorMessage)
                } else {
                    ElMessage.error('编辑二级科室失败，请检查网络连接')
                }
                return // 出错时不关闭对话框
            }
        } else {
            // 新增模式 - 调用后端API
            try {
                // 确保有选中的父级科室
                if (!currentParentDepartment.value) {
                    ElMessage.error('请先选择一级科室')
                    return
                }

                const requestData = {
                    departmentName: subDepartmentForm.name,
                    departmentStatus: subDepartmentForm.status === '显示',
                    departmentRemarks: subDepartmentForm.remarks || '',
                    parentId: currentParentDepartment.value.id  // 使用当前选中的父级科室ID
                }

                console.log('提交新增二级科室数据:', requestData)

                const response = await writeB.post('/api/Department/AddDepartment/add', requestData)

                console.log('新增二级科室响应:', response.data)

                if (response.data && (response.status === 200 || response.status === 201)) {
                    ElMessage.success('新增二级科室成功')

                    // 重新加载二级科室列表
                    if (currentParentDepartment.value) {
                        await loadSubDepartments(currentParentDepartment.value.id)
                    }

                    // 重新加载主科室列表
                    await loadDepartments()

                    // 重新加载一级科室数据
                    await loadAllFirstLevelDepartments()
                } else {
                    ElMessage.error('新增二级科室失败，请检查数据')
                }
            } catch (error: any) {
                console.error('新增二级科室失败:', error)

                // 检查错误响应
                if (error.response && error.response.data) {
                    const errorMessage = error.response.data.message || error.response.data.title || '新增二级科室失败'
                    ElMessage.error(errorMessage)
                } else {
                    ElMessage.error('新增二级科室失败，请检查网络连接')
                }
                return // 出错时不关闭对话框
            }
        }

        subDepartmentFormModalVisible.value = false

        // 重新加载二级科室列表
        if (currentParentDepartment.value) {
            await loadSubDepartments(currentParentDepartment.value.id)
        }
    } catch (error) {
        console.error('表单验证失败:', error)
    }
}

const resetSubDepartmentForm = () => {
    Object.assign(subDepartmentForm, {
        id: 0,
        name: '',
        parentId: 0, // 不再从表单获取parentId，而是从currentParentDepartment获取
        remarks: '',
        status: '显示'
    })
}
</script>

<style scoped>
.hospital-departments {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.table-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
}

.batch-operations {
    display: flex;
    align-items: center;
    gap: 10px;
}

.form-tip {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
}

.sub-department-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.sub-department-header h5 {
    margin: 0;
    color: #409eff;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>